package binpacking.algorithms;

import java.util.List;

import binpacking.model.Bin;
import binpacking.model.BinContainer;
import binpacking.model.Block;

public class NextFit {
	private List<Block> blocks;
	private BinContainer binContainer;
	private int binSize;

	public NextFit( List<Block> blocks, BinContainer binContainer, int binSize ) {
		this.blocks = blocks;
		this.binContainer = binContainer;
		this.binSize = binSize;
	}

	public void run() {
		/* The first bin isn't there yet. If there aren't any blocks, we don't need any bins */
		Bin bin = null;

		/* For every block we have.. */
		while( blocks.size() > 0 ) {
			
			/* Get the first block and remove it from the list */
			Block block = blocks.remove( 0 );

			/* If we have a bin and the bin has room */
			if( bin != null && bin.storageAvailable( block.getSize() ) ) {
				block.place();
				bin.addBlock( block );
			} else {
				/* We're going to have to make a new bin */
				bin = new Bin( binSize );
				
				/* Place the block inside */
				bin.addBlock( block );
				block.place();
				
				/* Add the bin to the container */
				binContainer.addBin( bin );
			}
		}
	}

	public String getResult() {
		return "Bins used: " + binContainer.getBins().size() + "\n" + binContainer.getVisualRepresentation();
	}
}
